//
//  YHUserAccountViewModel.swift
//  WeiBoYH
//
//  Created by yanhui on 2017/1/8.
//  Copyright © 2017年 yanhui. All rights reserved.
//

import UIKit

private let cacheAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("account.plist")

class YHUserAccountViewModel: NSObject {
    
    //设计单例对象
    static let shard: YHUserAccountViewModel = YHUserAccountViewModel()
    
    //持有 数据模型 处理数据
    var account: YHUserAccount?
    
    
    //定义access_token的属性
    var access_token: String? {
        return account?.access_token
    }
    
    var headUrl: URL? {
        
        return URL(string: account?.avatar_large ?? "")
        
    }
    override init() {
        super.init()
        
        self.account = self.loadUserAccount()
    }
    
    var userLogin: Bool {
        if account?.access_token != nil && isExpires == false {
            return true
        }
        
        return false
    }
    
    //判断token是否过期
    var isExpires: Bool {
        
        if account?.expires_date?.compare(Date()) == .orderedDescending {
            
            return false
        }
        
        return true
    }
    
    func loadAccessToken(code: String,finished: @escaping (Bool) -> ()) {
        //请求接口  获取令牌
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let dict = ["client_id" : client_id,
                    "client_secret" : client_secret,
                    "code" : code,
                    "grant_type" : "authorization_code",
                    "redirect_uri" : redirect_uri]
        //请求接口
        HMNetworkTools.shared.request(method: .POST, urlString: urlString, parameters: dict, finished: { (resp, error) -> () in
            if error != nil {
                //执行闭包
                finished(false)
                return
            }
            
            //3. 通过令牌请求用户信息
            self.loadUserInfo(dict:resp as! [String : Any], loadUserInfofinished: finished)
            //有可能用户信息没有获取成功就执行了回调
            
        })
    }
    
    
    //3. 通过令牌请求用户信息
    private func loadUserInfo(dict: [String : Any],loadUserInfofinished: @escaping (Bool) -> ()) {
        //参数: access_token  uid
        let access_token = dict["access_token"]!
        let uid = dict["uid"]!
        let parameters = ["access_token" : access_token,
                          "uid" : uid]
        print(parameters)
        let urlString = "https://api.weibo.com/2/users/show.json"
        HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (resp, error) in
            if error != nil {
                
                return
            }
            var userInfoDict = resp as! [String : Any]
            
            //3.1 将授权信息 和 用户信息合并在一起
            for (key,value) in dict {
                //设置键值对
                userInfoDict[key] = value
            }
            //3.2 将所有的信息转换为模型数据
            let userAccount = YHUserAccount(dict: userInfoDict)
            
            //调用归档的方法
            self.account = userAccount
            self.saveUserAccount(account: userAccount)
            //完成成功的回调
            loadUserInfofinished(true)
        }
    }
    
    
    //3. 封装数据缓存和数据获取的操作   存
        private func saveUserAccount(account: YHUserAccount) {
        //归档 到沙盒中Document/Library
        NSKeyedArchiver.archiveRootObject(account, toFile: cacheAccountPath)
    }
    
    //通过解档的方式获取用户信息的模型
    func loadUserAccount() -> YHUserAccount? {
        
        print(cacheAccountPath)
        if let cacheAccount = NSKeyedUnarchiver.unarchiveObject(withFile: cacheAccountPath) as? YHUserAccount{
          
            return cacheAccount
        }
        //默认无法获取用户模型对象
        return nil
    }
    
}

